package com.wzy.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 描述  :
 * scattering: 将数据写入到buffer时,可以采用buffer数组,依次写入[分散]
 * gathering: 从buffer读取数据时,可以采用buffer数组,依次读[聚集]
 * <p>
 * 创建人    Wzy
 * 创建时间: 2020-05-20  16:42
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        //使用 ServerSocketChannel 和 socketChannel网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        serverSocketChannel.socket().bind(inetSocketAddress);

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        SocketChannel socketChannel = serverSocketChannel.accept();

        int messageLength = 8;
        //循环的读取
        while (true) {
            int byteRead = 0;

            while (byteRead < messageLength) {
                long l = socketChannel.read(byteBuffers);
                byteRead += l;
                System.out.println("byteRead=" + byteRead);

                Arrays.stream(byteBuffers).map(buffer -> {
                    return "position=" + buffer.position() + ",limit" + buffer.limit();
                }).forEach(System.out::println);
            }
            //将所有buffer输出
            for (ByteBuffer byteBuffer : byteBuffers) {
                byteBuffer.flip();
            }
            //数据独处显示客户端
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }
            //将所有的buffer clear
            for (ByteBuffer byteBuffer : byteBuffers) {
                byteBuffer.clear();
            }
            System.out.println("byteRead:=" + byteRead + "byteWrite" + byteWrite + ",messageLength"
                    + messageLength);

        }

    }
}
